﻿using B.S.Medical.Api.Read.Application.Command.Department;
using B.S.Medical.Api.Read.DTOS;
using B.S.Medical.Domain.Department;
using B.S.Medical.Domain.Doctor;
using B.S.Medical.ErrorCode;
using B.S.Medical.Infrastructure.Interface;
using MediatR;

namespace B.S.Medical.Api.Read.Application.Handler.Department
{
    public class ManagePageCommandHandler : IRequestHandler<ManagePageCommand, ApiPageing<ManageModelDTO>>
    {
        private readonly IBaseRepository<ManageModel> _manageModelRepository;
        private readonly IBaseRepository<DoctorModel> _doctorModelRepository;
        private readonly IBaseRepository<CampusModel> _campusModelRepository;

        public ManagePageCommandHandler(IBaseRepository<ManageModel> manageModelRepository, IBaseRepository<DoctorModel> doctorModelRepository, IBaseRepository<CampusModel> campusModelRepository)
        {
            _manageModelRepository = manageModelRepository;
            _doctorModelRepository = doctorModelRepository;
            _campusModelRepository = campusModelRepository;
        }

        public Task<ApiPageing<ManageModelDTO>> Handle(ManagePageCommand request, CancellationToken cancellationToken)
        {
            ApiPageing<ManageModelDTO> res = new ApiPageing<ManageModelDTO>();
            var manage = _manageModelRepository.GetAll().Where(x => x.IsDeleted == false);
            var campus = _campusModelRepository.GetAll().Where(x => x.IsDeleted == false);
            if (!string.IsNullOrEmpty(request.DepartmentName))
            {
                manage = manage.Where(x => x.DepartmentName.Contains(request.DepartmentName));
            }

            var list = from a in manage
                       join b in campus on a.CampusId equals b.Id
                       select new ManageModelDTO
                       {
                           Id = a.Id,
                           CampusName = b.CampusName,
                           ParetId = a.ParetId,
                           DepartmentName = a.DepartmentName,
                           CampusId = a.CampusId,
                           DepartmentAddr = a.DepartmentAddr,
                           Status = a.Status
                       };
            res.TotaCount = list.Count();
            res.PageData = list.OrderByDescending(x => x.Id).Skip((request.Index - 1) * request.Size).Take(request.Size).ToList();
            res.Code = ApiEnum.Success;
            res.Msg = "查询成功!";
            return Task.FromResult(res);
        }
    }
}
